package rursu.dal.managers;

import java.util.ArrayList;
import java.util.List;

import rursu.dal.managers.interfaces.IMoviesListPairDAL;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MoviesListPairDALManager implements IMoviesListPairDAL {

	private SQLiteDatabase db;
	
	public static final String TABLE_NAME = "list_movie_pair";	
		
	protected static final String MOVIE_ID = "movie_id";	
	protected static final String LIST_ID = "list_id";
	protected static final String ID = "_id";
	
	public MoviesListPairDALManager(SQLiteDatabase db) {
		this.db = db;
	}

	public long insert(int movieId, int listId) {
		
		ContentValues values = new ContentValues();
		
        values.put(MoviesListPairDALManager.MOVIE_ID, movieId);
        values.put(MoviesListPairDALManager.LIST_ID, listId);

        return db.insert(TABLE_NAME, null, values);
	}

	public void deleteMovies(int movieId) {
		db.delete(TABLE_NAME, MoviesListPairDALManager.MOVIE_ID + "=" + movieId, null);		
	}

	public void deleteMoviesList(int listId) {
		db.delete(TABLE_NAME, MoviesListPairDALManager.LIST_ID + "=" + listId, null);
	}

	public void deletePair(int movieId, int listId) {
		db.delete(TABLE_NAME, MoviesListPairDALManager.MOVIE_ID + "=" + movieId + ", " + MoviesListPairDALManager.LIST_ID + "=" + listId, null);
	}

	public List<Integer> getMovieIds(int listId) {
		
		Cursor cursor = db.query(TABLE_NAME, new String [] {
				MoviesListPairDALManager.ID, 
				MoviesListPairDALManager.MOVIE_ID},				
				MoviesListPairDALManager.LIST_ID + "=" + listId, null, null, null, null);
		

		List<Integer> ids = new ArrayList<Integer>();
		
		cursor.moveToFirst();
		
		while ( !cursor.isAfterLast() ) {
			
			Integer id = cursor.getInt( cursor.getColumnIndex(MoviesListPairDALManager.MOVIE_ID) );
			
			ids.add(id);
			
			cursor.moveToNext();
		}		
		
		cursor.close();
		return (ids.isEmpty()) ? null : ids;
	}

	public List<Integer> getMoviesListIds(int movieId) {
		Cursor cursor = db.query(TABLE_NAME, new String [] {
				MoviesListPairDALManager.ID, 
				MoviesListPairDALManager.LIST_ID},				
				MoviesListPairDALManager.MOVIE_ID + "=" + movieId, null, null, null, null);
		

		List<Integer> ids = new ArrayList<Integer>();
		
		cursor.moveToFirst();
		
		while ( !cursor.isAfterLast() ) {
			
			Integer id = cursor.getInt( cursor.getColumnIndex(MoviesListPairDALManager.LIST_ID) );
			
			ids.add(id);
			
			cursor.moveToNext();
		}		
		
		cursor.close();
		
		return (ids.isEmpty()) ? null : ids;
	}

	public int updateListId(int oldValue, int newValue) {
		
		ContentValues values = new ContentValues();
        values.put(MoviesListPairDALManager.LIST_ID, newValue);
		
        return db.update(TABLE_NAME, values, MoviesListPairDALManager.LIST_ID + "=" + oldValue, null);
	}

	

	

}
